<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--基本信息-->
			<view class="detail-item">
				<uni-section title="基本信息" type="line"></uni-section>
				<view class="detail-content" v-if="info.id">
					<view class="detail-text">区域：<text>{{arrText(setStore.allProvinceList, info.regionCode)}}</text></view>
					<view class="detail-text">
						商品名称：
						<text>{{info.name}}</text>
						<text class="detail-text-copy" @click.stop="copyText(info.name)">复制</text>
					</view>
					<view class="detail-text">
						商品编码：
						<text>{{info.code}}</text>
						<text class="detail-text-copy" @click.stop="copyText(info.code)">复制</text>
					</view>
					<view class="detail-text">
						商品条码：
						<text>{{info.barcode}}</text>
						<text class="detail-text-copy" @click.stop="copyText(info.barcode)">复制</text>
					</view>
					<view class="detail-text main-flex">
						是否采购：
						<uni-tag size="small" :type="info.purchaseFlag === 1 ? 'success' : ''" :text="info.purchaseFlag === 1 ? '是' : '否'" />
					</view>
					<view class="detail-text main-flex">
						是否样品：
						<up-switch
							v-if="checkPermi(['zhouyz:productInfo:trialProduct'])"
							:activeValue="1"
							:inactiveValue="0"
							v-model="info.trialProduct"
							asyncChange
							@change="trialProductChange"
							size="20" >
						</up-switch>
						<uni-tag v-else size="small" :type="info.trialProduct === 1 ? 'success' : ''" :text="info.trialProduct === 1 ? '是' : '否'" />
					</view>
					<view class="detail-text main-flex">
						销售可提：
						<up-switch
							v-if="checkPermi(['zhouyz:productInfo:salesDemand'])"
							:activeValue="1"
							:inactiveValue="0"
							v-model="info.salesDemand"
							asyncChange
							@change="salesDemandChange"
							size="20" >
						</up-switch>
						<uni-tag v-else size="small" :type="info.salesDemand === 1 ? 'success' : ''" :text="info.salesDemand === 1 ? '是' : '否'" />
					</view>
					<view class="detail-text main-flex">
						是否冻结：
						<up-switch
							v-if="checkPermi(['zhouyz:productInfo:freeze'])"
							:activeValue="1"
							:inactiveValue="0"
							v-model="info.freeze"
							asyncChange
							@change="freezeChange"
							size="20" >
						</up-switch>
						<uni-tag v-else size="small" :type="info.freeze === 1 ? 'error' : ''" :text="info.freeze === 1 ? '是' : '否'" />
					</view>
					<view class="detail-text">商品卖点：<text>{{info.marketTitle}}</text></view>
					<view class="detail-text">关键词：<text>{{info.keyword}}</text></view>
					<!-- <view class="detail-text">类型名称：<text>{{arrText(productTypeList, info.typeId)}}</text></view> -->
					<view class="detail-text">商品单位：<text>{{info.unit}}</text></view>
					<view class="detail-text main-flex">商品归类：<uni-tag size="small" :text="arrText(productClassifyList, info.productClassify)" /></view>
					<view class="detail-text">销量：<text>{{info.salesNumber}}</text></view>
					<view class="detail-text">库存：<text>{{info.stock}}</text></view>
					<view class="detail-text">重量(Kg)：<text>{{info.productWeight}}</text></view>
					<view class="detail-text">
						存储类型：
						<uni-tag :class="`storeType${info.storeType}`" size="small" :text="arrText(storeTypeList, info.storeType)" />
					</view>
					<view class="detail-text">存货编码：<text>{{info.storeCode}}</text></view>
					<view class="detail-text">备注：<text>{{info.remark}}</text></view>
					<view class="detail-text main-flex">
						送积分：
						<uni-tag size="small" :type="info.sendIntegralFlag === 1 ? 'success' : ''" :text="info.sendIntegralFlag === 1 ? '是' : '否'" />
						<text v-if="info.sendIntegralFlag === 1" class="detail-text-integral">(送{{info.sendIntegralValue}}积分，最多{{info.mastSendIntegral}}积分)</text>
					</view>
				</view>
			</view>
			<!--拆分组合-->
			<view class="detail-item" v-if="(info?.productClassify === 3 || info?.productClassify === 4) && checkPermi(['zhouyz:productMix:list'])">
				<uni-section title="拆分组合" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-content table">
						<ty-table
							:data="productMixList"
							:columns="productMixColumns"
							:sortable="true"
							:cellClassName="() => 'table-cell'"
							:headerCellClassName="() => 'table-cell'"
							:rowClassName="() => 'table-row'"
							stripe
							border>
							<template v-slot:img="{ row }">
								<view class="detail-text_r" v-if="row?.product?.image" @click.stop="previewImg(row?.product?.image)">
									<up-image width="120rpx" height="120rpx" :src="row?.product?.image" :lazy-load="true"></up-image>
								</view>
							</template>
							<template v-slot:left="{ row }">
								<view class="table-td-cell" v-if="row?.product">
									<!-- <view class="table-td-row">
										ID：
										<text class="table-td-text">{{row?.product?.id}}</text>
									</view> -->
									<view class="table-td-row">
										区域：
										<uni-tag size="small" type="primary" :text="arrText(setStore.allProvinceList, row?.product?.regionCode)" />
									</view>
									<view class="table-td-row">
										名称：
										<text class="table-td-text">{{row?.product?.name}}</text>
									</view>
								</view>
							</template>
							<template v-slot:center="{ row }">
								<view class="table-td-cell" v-if="row?.product">
									<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">批发：<text class="table-td-text">{{row?.product?.wholePrice}}</text></view>
									<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">零售：<text class="table-td-text">{{row?.product?.retailPrice}}</text></view>
									<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">团购：<text class="table-td-text">{{row?.product?.groupPrice}}</text></view>
									<view class="table-td-row" v-if="checkPermi(['zhouyz:productPrice:list'])">超市：<text class="table-td-text">{{row?.product?.shopPrice}}</text></view>
								</view>
							</template>
							<template v-slot:right="{ row }">
								<view class="table-td-cell">
									<view class="table-td-row">
										单位：
										<text class="table-td-text">{{row?.product?.unit}}</text>
									</view>
									<view class="table-td-row">
										数量：
										<text class="table-td-text">{{row.childrenCount}}</text>
									</view>
								</view>
							</template>
						</ty-table>
					</view>
					<view class="mix" v-if="info.productClassify === 3">
						<view class="mix-item">{{`【${info.name}】 * 1 = 以下商品组合：`}}</view>
						<view class="mix-item" v-for="item in productMixList" :key="item.id">
							{{`【${item?.product?.name}】 * ${item.childrenCount}`}}
						</view>
					</view>
					<view class="mix" v-else-if="info.productClassify === 4">
						<view class="mix-item">
							{{`【${productMixList[0]?.product?.name}】 * 1 = 拆分成以下商品：`}}
						</view>
						<view class="mix-item">{{`【${info.name}】 * ${productMixList[0]?.childrenCount}`}}</view>
					</view>
				</view>
			</view>
			<!--商品价格-->
			<view class="detail-item" v-if="checkPermi(['zhouyz:purchaseOrder:price', 'zhouyz:productInfo:price', 'zhouyz:productPrice:list'])">
				<uni-section title="商品价格" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-text" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">采购价：<text>{{info.purchasePrice}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:productInfo:price'])">最低售价：<text>{{info.sellPrice}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:productInfo:price'])">市场价：<text>{{info.marketPrice}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:productPrice:list'])">渠道设置：</view>
					<view class="detail-content table" v-if="checkPermi(['zhouyz:productPrice:list'])">
						<ty-table
							:data="tableList"
							:columns="columns"
							:sortable="true"
							:cellClassName="() => 'table-cell'"
							:headerCellClassName="() => 'table-cell'"
							:rowClassName="() => 'table-row'"
							stripe
							border>
							<template v-slot:sellChannel="{ row }">
								<uni-tag size="small" type="primary" :text="arrText(sellChannelList, row.sellChannel)" />
							</template>
							<template v-slot:opened="{ row }">
								<uni-tag size="small" :type="row.opened === 1 ? 'success' : ''" :text="row.opened === 1 ? '开启' : '关闭'" />
							</template>
							<template v-slot:remark="{ row }">
								<text class="table-td-text">{{row.remark}}</text>
							</template>
						</ty-table>
					</view>
				</view>
			</view>
			<!--规格商品-->
			<view class="detail-item">
				<uni-section title="规格商品" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-content table">
						<ty-table
							:data="specsList"
							:columns="productListColumns"
							:sortable="true"
							@row-click="rowClick"
							:cellClassName="() => 'table-cell'"
							:headerCellClassName="() => 'table-cell'"
							:rowClassName="() => 'table-row'"
							stripe
							border>
							<template v-slot:status="{ row }">
								<uni-tag :type="row.status === 1 ? 'success' : 'error'" size="small" :text="row.status === 1 ? '上架' : '下架'" />
							</template>
						</ty-table>
					</view>
				</view>
			</view>
			<!--关联商品-->
			<view class="detail-item">
				<uni-section title="关联商品" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-content table">
						<ty-table
							:data="relationList"
							:columns="productListColumns"
							:sortable="true"
							@row-click="rowClick"
							:cellClassName="() => 'table-cell'"
							:headerCellClassName="() => 'table-cell'"
							:rowClassName="() => 'table-row'"
							stripe
							border>
							<template v-slot:status="{ row }">
								<uni-tag :type="row.status === 1 ? 'success' : 'error'" size="small" :text="row.status === 1 ? '上架' : '下架'" />
							</template>
						</ty-table>
					</view>
				</view>
			</view>
			<!--商品视图-->
			<view class="detail-item">
				<uni-section title="商品视图" type="line"></uni-section>
				<view class="detail-content">
					<view class="main-flex detail-text detail-flex-start">
						商品主图：
						<view class="detail-text_r" @click.stop="previewImg(info.image)">
							<up-image width="120rpx" height="120rpx" :src="info.image" :lazy-load="true"></up-image>
						</view>
					</view>
					<view class="main-flex detail-text detail-flex-start">
						banner图：
						<view class="detail-text_r detail-text-banners main-flex main-flex-item detail-flex-wrap">
							<up-image
								v-for="item in bannerList"
								:key="item"
								class="detail-text-banner"
								width="120rpx"
								height="120rpx"
								@click.stop="previewImg(item, bannerList)"
								:src="item"
								:lazy-load="true"></up-image>
						</view>
					</view>
					<view class="main-flex detail-text detail-flex-start" v-if="info.videoCoverImage">
						视频封面：
						<view class="detail-text_r" @click.stop="previewImg(info.videoCoverImage)">
							<up-image width="120rpx" height="120rpx" :src="info.videoCoverImage" :lazy-load="true"></up-image>
						</view>
					</view>
					<view class="main-flex detail-text detail-flex-start" v-if="info.video">
						商品视频：
						<view class="detail-text_r main-flex-item">
							<video
								id="video"
								class="detail-text-video"
								src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4"
							  :poster="info.videoCoverImage"
								controls>
							</video>
						</view>
					</view>
					
					<view class="main-flex detail-text detail-flex-start">
						商品详情：
						<view class="detail-text_r product-content">
							<up-parse :content="info.detail"></up-parse>
						</view>
					</view>
					
				</view>
			</view>
			
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import {
	productDetail,
	productType,
	updateTrialProduct,
	updateSalesDemand,
	productMix,
	updateFreeze } from "@/api/erp_api/product"
import { allProvince } from "@/api/erp_api/region"
import { copyText, arrText, previewImg } from '@/utils/ty.js';
import { productClassifyList, sellChannelList, storeTypeList } from '@/utils/config.js';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
	
	const userStore = useUserStore()	
	const setStore = useSetStore()
	onLoad(async (option) => {
		if (option.id) {
			id.value = option.id
			// await getProductType()
			getDetail()
		}
	})
	
	// 获取商品类别
	// const productTypeList = ref([])
	// const getProductType = () => {
	// 	return productType({
	// 		sellChannel: 1
	// 	}).then(res => {
	// 		productTypeList.value = res.rows.map(item => {
	// 			return {
	// 				...item,
	// 				value: item.id,
	// 				text: `${item.parentName}->${item.name}`
	// 			}
	// 		}).filter(item => item.parentId) || []
	// 	})
	// }
	
	// 数据查询
	const id = ref('')
	const info = ref({})
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '渠道', key: 'sellChannel', align: 'center' },
		{ title: '是否开启', key: 'opened', align: 'center' },
		{ title: '销售价', key: 'sellPrice', align: 'center' },
		{ title: '起订数量', key: 'minimum', align: 'center' },
		{ title: '货运成本', key: 'logisticsCost', align: 'center' },
		{ title: '备注', key: 'remark', align: 'center', width: '180rpx' }
	])
	
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		productDetail(params).then(res => {
			info.value = res.data || {}
			tableList.value = res.data.priceList || []
			isLoading.value = false
			if (res.data?.productClassify === 3 || res.data?.productClassify === 4) {
				getProductMix(res.data)
			}
			getSpecsList(res?.data?.specsList)
			getRelationList(res?.data?.relationList)
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// banner图
	const bannerList = computed(() => {
		return info.value.banner ? info.value.banner.split(',').filter(item => item) : []
	})
	
	// 拆分组合
	const productMixList = ref([])
	// 表格头部
	const productMixColumns = ref([
		{ title: '商品图片', key: 'img', width: '140rpx' },
		{ title: '商品信息', key: 'left' },
		{ title: '价格', key: 'center', width: '180rpx' },
		{ title: '单位数量', key: 'right' }
	])
	const getProductMix = (item) => {
		const params = {
			pageNum: 1,
			pageSize: 100,
			productClassify: item.productClassify
		}
		if (item.productClassify === 3) {
			params.parentId = item.id
		} else if (item.productClassify === 4) {
			params.childrenId = item.id
		}
		productMix(params).then(async (res) => {
			if (res.rows) {
				for (let i= 0; i < res.rows.length; i++) {
					const productOne = await productDetail({id: item.productClassify === 3 ? res.rows[i].childrenId : res.rows[i].parentId})
				  productMixList.value.push({
						...res.rows[i],
						product: productOne?.data
					})
				}
			}
			// console.log(productMixList.value)
		})
	}
	
	// 切换是否样品
	const trialProductChange = (e) => {
		uni.showModal({
			content: `确认要修改该商品的是否样品为${ e === 1 ? '开启' : '关闭' }吗?`,
			success: (res) => {
				if (res.confirm) {
					updateTrialProduct({
						id: id.value,
						trialProduct: e
					}).then(res => {
						getDetail()
						uni.$emit('refreshList');  // 触发刷新事件
					})
				}
			}
		})
	}
	
	// 切换销售可提
	const salesDemandChange = (e) => {
		uni.showModal({
			content: `确认要修改该商品的销售可提为${ e === 1 ? '开启' : '关闭' }吗?`,
			success: (res) => {
				if (res.confirm) {
					updateSalesDemand({
						id: id.value,
						salesDemand: e
					}).then(res => {
						getDetail()
						uni.$emit('refreshList');  // 触发刷新事件
					})
				}
			}
		})
	}
	
	// 切换是否冻结
	const freezeChange = (e) => {
		uni.showModal({
			content: `确认要修改该商品的是否冻结为${ e === 1 ? '开启' : '关闭' }吗?`,
			success: (res) => {
				if (res.confirm) {
					updateFreeze({
						id: id.value,
						freeze: e
					}).then(res => {
						getDetail()
						uni.$emit('refreshList');  // 触发刷新事件
					})
				}
			}
		})
	}
	
	const specsList = ref([])
	const productListColumns = ref([
		{ title: '商品名称', key: 'name' },
		{ title: '单位', key: 'unit', width: '160rpx', align: 'center' },
		{ title: '状态', key: 'status', width: '100rpx', align: 'center' }
	])
	const getSpecsList = async (ids) => {
		if (ids) {
			const idsArr = ids.split(',')
			for(let i = 0; i < idsArr.length; i++) {
				const product = await productDetail({id: idsArr[i]})
				if (product.code === 200) {
					specsList.value.push({...product.data})
				} else {
					specsList.value.push({
						name: '商品信息错误',
						status: 0,
						unit: ''
					})
				}
			}
		}
	}
	const relationList = ref([])
	const getRelationList = async (ids) => {
		if (ids) {
			const idsArr = ids.split(',')
			for(let i = 0; i < idsArr.length; i++) {
				const product = await productDetail({id: idsArr[i]})
				if (product.code === 200) {
					relationList.value.push({...product.data})
				} else {
					relationList.value.push({
						name: '商品信息错误',
						status: 0,
						unit: ''
					})
				}
			}
		}
	}
	// 点击行
	const rowClick = (row) => {
		uni.navigateTo({
			url: `/pages/product/productDetail?id=${row.id}`
		})
	}
	
	
</script>

<style scoped lang="scss">
.detail-text-integral {
	margin-left: 20rpx;
}
.detail-text-banners {
	margin-left: -10rpx;
}
.detail-text-banner {
	margin: 0 10rpx 10rpx;
}
.detail-text-video {
	width: 100%;
	height: 250rpx;
}
.table {
	padding: 0;
	margin-top: 20rpx;
}
.product-content {
	width: 570rpx;
}
.mix {
	font-size: 12px;
	color: red;
	margin-top: 10rpx;
	&-item {
		&+.mix-item {
			text-indent: 2em;
		}
	}
}
.storeType1 {
	background-color: #FFA726;
	border-color: #FFA726;
}
.storeType2 {
	background-color: #4FC3F7;
	border-color: #4FC3F7;
}
.storeType3 {
	background-color: #B3E5FC;
	border-color: #B3E5FC;
}
</style>
